package com.yssoft.controller.app.purchase;

import com.google.common.collect.Lists;
import com.yssoft.entity.core.TSupplier;
import com.yssoft.entity.inspection.TInspReport;
import com.yssoft.entity.purchase.TPurchaseInfo;
import com.yssoft.service.core.SupplierService;
import com.yssoft.service.purchase.DemandInfoService;
import com.yssoft.service.purchase.PurchaseInfoService;
import com.yssoft.utils.AppUtil;
import com.yssoft.utils.ObjectConversion;
import org.apache.commons.codec.DecoderException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author 陈翼东
 * @说明 订单(采购单)管理
 * @time 2018/4/29 下午 02:18
 */
@CrossOrigin//解决跨域session问题
@RestController
@RequestMapping("/app/purchaseOrder")
public class PurchaseOrderController {
    
    @Resource
    private PurchaseInfoService purchaseInfoService;
    
    @Resource
    private DemandInfoService demandInfoService;
    
    @Resource
    private SupplierService supplierService;
    
    
    /**
     * 获取申请单和详情ok
     *
     * @param currentPage            当前页数
     * @param pageSize           每页条数
     * @param companyId          企业id
     * @param goodsClassifyId 物料类型
     * @param goodsName       物料名称
     * @return
     */
    @RequestMapping(value = "getPurchaseRequestList", method = RequestMethod.POST)
    public Object getPurchaseRequestList(int currentPage, int pageSize, String companyId,String goodsClassifyId, String goodsName) {
        if (companyId == null) {
            return AppUtil.returnMapJson("0", "查询失败，请传递企业id", null);
        }else{
            try {
                List<Map<String, Object>> demandInfo = demandInfoService.findPageByApplied(currentPage, pageSize, Integer.parseInt(companyId), goodsClassifyId, goodsName);
                return AppUtil.returnListJson("1", "查询成功!", demandInfo);
            } catch (NumberFormatException e) {
                return AppUtil.returnListJson("0", "查询失败!" + e.getMessage(), null);
            }
        }
    }
    
    /**
     * 查询采购单和详情ok
     * @param companyId
     * @param goodsClassifyId
     * @param goodsName
     * @param pageSize
     * @param currentPage
     * @return
     */
    @RequestMapping(value = "getPurchaseOrderList", method = RequestMethod.POST)
    public Object getPurchaseOrderList(String companyId, String goodsClassifyId, String goodsName, int pageSize, int currentPage) {
        try {
            List<Map<String, Object>> purchaseInfo = purchaseInfoService.findPage(currentPage, pageSize, Integer.parseInt(companyId), goodsClassifyId, goodsName);
            return AppUtil.returnListJson("1", "查询成功!", purchaseInfo);
        } catch (NumberFormatException e) {
            return AppUtil.returnListJson("0", "查询失败!" + e.getMessage(), null);
        }
    }
    
    
    /**
     * 将申请单转换成采购订单ok
     *
     * @return
     */
    @RequestMapping(value = "/buildPurchaseOrderBy", method = RequestMethod.POST)
    public Object buildPurchaseOrderBy(String[] id,String[] singlePrice,String[] remark,String[] deliveryDate, String entId,HttpServletRequest request) {
        try {
            return purchaseInfoService.demandSavePurchase(id,singlePrice,remark,deliveryDate, entId,request);
        } catch (Exception e) {
            return AppUtil.returnMapJson("0","保存失败"+e.getMessage(),null);
        }
    }
    
    /**
     * 退回订单采购单详情
     *
     * @param purchaseRequestId
     * @return
     */
    @RequestMapping(value = "returnPurchaseRequest",method = RequestMethod.POST)
    public Object returnPurchaseRequest(String purchaseRequestId) {
        return purchaseInfoService.updateDemandInfoStat(purchaseRequestId, "3");
    }
    
    /**
     * 获取我的供应商ok
     * @param companyId
     * @param name
     * @return
     */
    @RequestMapping(value = "getSupplierListByCompanyId", method = RequestMethod.POST)
    public Object getSupplierListByCompanyId(String companyId, String name,int pageSize ,int currentPage) {
        try {
            List<TSupplier> supplierList = purchaseInfoService.findMySupplier(companyId, name,pageSize,currentPage);
            return AppUtil.returnListObjectJson("1", "获取我的供应商成功!", supplierList);
        } catch (IllegalAccessException e) {
            return AppUtil.returnListJson("0", "获取我的供应商失败!" + e.getMessage(), null);
        }
    }
    
    /**
     * 删除一条采购单ok
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "deletePurchaseOrderById", method = RequestMethod.POST)
    public Object deletePurchaseOrderById(String id) {
        return purchaseInfoService.deleteOne(id);
    }
    
    /**
     * 保存补录采购单ok
     *
     * @param realPrice  实际价格
     * @param reciveDate 交货日期
     * @param remark     备注信息
     * @param quantity   数量信息
     * @param totalPrice
     * @param supplierId
     * @return
     */
    @RequestMapping(value = "savePurchaseOrder", method = RequestMethod.POST)
    public Object savePurchaseOrder(HttpServletRequest request,String[] realPrice, String[] reciveDate, String[] remark, String[] mid, String[] quantity, String totalPrice, String supplierId) throws IOException, DecoderException {
        return purchaseInfoService.savePurchaseInfo(realPrice, reciveDate, remark, mid, quantity, totalPrice, supplierId,request);
    }
    
    /**
     * 查询收货单ok
     * @param purchaseOrderDetailId
     * @return
     */
    @RequestMapping(value = "getReciveDocumentListByPurchaseOrderDetailId", method = RequestMethod.POST)
    public Object getReciveDocumentListByPurchaseOrderDetailId(String purchaseOrderDetailId) throws IllegalAccessException {
        try {
            Map<String,Object> recipientDetailList=purchaseInfoService.findRecipientByPurchaseDetailId(purchaseOrderDetailId);
            return  AppUtil.returnMapJson("1","获取成功!",recipientDetailList);
        } catch (Exception e) {
            return  AppUtil.returnMapJson("0","获取失败"+e.getMessage(),null);
        }
    }
    
    /**
     * 上传补录订单的合同ok
     * @param request
     * @param purchaseInfoId
     * @return
     */
    @RequestMapping(value = "uploadContract", method = RequestMethod.POST)
    public Object uploadContract(HttpServletRequest request, String purchaseInfoId) throws IOException, DecoderException {
        try {
            MultipartRequest multipartRequest=(MultipartRequest)request;
            Iterator<String> fileNames = multipartRequest.getFileNames();
            Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
            List<MultipartFile> files = Lists.newArrayList();
            while (fileNames.hasNext()){
                files.add(fileMap.get(fileNames.next()));
            }
            return  purchaseInfoService.uploadContract(files,purchaseInfoId,request);
        } catch (Exception e) {
            return AppUtil.returnMapJson("0","保存失败"+e.getMessage(),null);
        }
    }
    /**
     * 获取补录订单的合同ok
     * @param purchaseInfoId
     * @return
     */
    @RequestMapping(value = "getContract", method = RequestMethod.POST)
    public Object getContract(String purchaseInfoId){
        try {
            return  purchaseInfoService.getContract(purchaseInfoId);
        } catch (Exception e) {
            return AppUtil.returnMapJson("0","保存失败"+e.getMessage(),null);
        }
    }
    
    /**
     * 获取多个申请单
     * @param ids
     * @return
     */
    @RequestMapping(value = "getApplicationForm", method = RequestMethod.POST)
    public Object getApplicationForm(String ids){
        try {
            return  purchaseInfoService.findApplicationFormByid(ids);
        } catch (Exception e) {
            return AppUtil.returnMapJson("0","获取失败"+e.getMessage(),null);
        }
    }
    
    /**
     * 获取要修改订单的信息
     * @return
     */
    @RequestMapping(value = "selectPurchase", method = RequestMethod.POST)
    public Object selectPurchase(String purchaseInfoId){
        if(purchaseInfoId==null){
            return AppUtil.returnMapJson("0","请传递订单的id",null);
        }else{
            TPurchaseInfo purchaseInfo = purchaseInfoService.findOne(purchaseInfoId);
            List<Map<String,Object>> detailList=purchaseInfoService.findDetailByInfo(purchaseInfo.getId());
            try {
                Integer sid = purchaseInfo.gettSId();//供应商id
                TSupplier supplier = supplierService.selectByPrimaryKey(sid);
                Map<String, Object> infoMap = ObjectConversion.getObjectToMap(purchaseInfo);
                if(supplier!=null){
                    infoMap.put("supplierName",supplier.getName());
                }
                List<Map<String,Object>>  imgList= purchaseInfoService.findPurchaseImg(purchaseInfo.getId());
                infoMap.put("purchaseOrderDetailList",detailList);
                infoMap.put("imgList",imgList);
                
                return AppUtil.returnMapJson("1","查询成功",infoMap);
            } catch (IllegalAccessException e) {
                return AppUtil.returnMapJson("0","查询失败"+e.getMessage(),null);
            }
        }
    }
    
    /**
     * 修改补录采购单(删除原来的详情，新加详情)
     *
     * @param realPrice  实际价格
     * @param reciveDate 交货日期
     * @param remark     备注信息
     * @param quantity   数量信息
     * @param totalPrice
     * @param supplierId
     * @return
     */
    @RequestMapping(value = "updatePurchaseOrder", method = RequestMethod.POST)
    public Object updatePurchaseOrder(HttpServletRequest request,String[] realPrice, String[] reciveDate, String[] remark, String[] mid, String[] quantity, String totalPrice, String supplierId,String purchaseInfoId) {
        try {
            return purchaseInfoService.updatePurchaseInfo(realPrice, reciveDate, remark, mid, quantity, totalPrice, supplierId,request,purchaseInfoId);
       } catch (Exception e) {
            return AppUtil.returnMapJson("0","保存失败"+e.getMessage(),null);
        }
    }
    
}
